package com.waiting.mq.config;

import com.rabbitmq.client.AMQP;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Exchange;
import org.springframework.amqp.core.Queue;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

@Configuration
public class RabbitConfig {

    /**
     * 訂單消息隊列
     */
    @Bean
    public Queue orderQueue() {

        Map<String, Object> props = new HashMap<>();

        // 消息的生存时间 5s
        props.put("x-message-ttl", 5000);
        // 设置该队列所关联的死信交换器（当队列消息TTL到期后依然没有消费，则加入死信队列）
        props.put("x-dead-letter-exchange", "ex.order.dlx");
        // 设置该队列所关联的死信交换器的routingKey，如果没有特殊指定，使用原队列的routingKey
        props.put("x-dead-letter-routing-key", "order.dlx");

        return new Queue("q.order", true, false, false, props);
    }

    /**
     * 訂單交換器
     */
    @Bean
    public Exchange orderExchange() {
        return new DirectExchange("ex.order", false, false);
    }

    /**
     * 訂單隊列與交換器綁定
     */
    @Bean
    public Binding orderBinding() {
        return new Binding("q.order", Binding.DestinationType.QUEUE, "ex.order",
                "order", null);
    }



    /**
     * 訂單死信隊列
     */
    @Bean
    Queue orderQueueDlx() {
        Queue queue = new Queue("q.order.dlx", true, false, false, null);
        return queue;
    }

    /**
     * 訂單死信交換器
     */
    @Bean
    public Exchange orderExchangeDlx() {
        return new DirectExchange("ex.order.dlx", false, false);
    }


    /**
     * 死信隊列與死信交換器綁定
     */
    @Bean
    public Binding orderDlxBinding() {
        return new Binding("q.order.dlx", Binding.DestinationType.QUEUE, "ex.order.dlx",
                "order.dlx", null);
    }

}
